//
// Created by kyour on 9/1/2023.
//

#include <esp_camera.h>
#include "ws_service.h"

WebSocketsClient webSocket;

void initWs()
{
    Serial.println("开始连接Ws");

    // server address, port and URL
    webSocket.begin("tx.kyour.cn", 8131, "/");

    // event handler
    webSocket.onEvent(webSocketEvent);

    // use HTTP Basic Authorization this is optional remove if not needed
//    webSocket.setAuthorization("user", "Password");

    // try ever 5000 again if connection has failed
    webSocket.setReconnectInterval(5000);

    Serial.println("配置Ws完成");

}

/**
 * ws事件监听
 * @param type
 * @param payload
 * @param length
 */
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[WSc] Disconnected!\n");
            break;
        case WStype_CONNECTED:
            Serial.printf("[WSc] Connected to url: %s\n", payload);

            // send message to server when Connected
            webSocket.sendTXT("logi:push");
            captureVideo();
            break;
        case WStype_TEXT:

            if(strcmp((char *)payload, (char *)"push") == 0){
//                Serial.println("[WSc]  请求推流");
                captureVideo();
            }

            // send message to server
            // webSocket.sendTXT("message here");
            break;
        case WStype_BIN:
            Serial.printf("[WSc] get binary length: %u\n", length);
//            hexdump(payload, length);

            // send data to server
            // webSocket.sendBIN(payload, length);
            break;
        case WStype_ERROR:
        case WStype_FRAGMENT_TEXT_START:
        case WStype_FRAGMENT_BIN_START:
        case WStype_FRAGMENT:
        case WStype_FRAGMENT_FIN:
            break;
    }

}

void sendBin(uint8_t * payload, size_t length)
{
    webSocket.sendBIN(payload, length);
}

bool wsIsConnected()
{
    return webSocket.isConnected();
}

void wsLoop()
{
    webSocket.loop();
}

/**
 * 捕获视频Loop
 */
void captureVideo() {
    camera_fb_t *fb = NULL;

    fb = esp_camera_fb_get();
    if (NULL == fb) {
        Serial.println("Camera capture failed");
    } else {
//        Serial.println(fb->len);
//        webSocket.sendBIN(fb->buf, fb->len);
        sendBin(fb->buf, fb->len);
        esp_camera_fb_return(fb);
        fb = NULL;
    }
}